package cn.tedu.oa_system.controller;

import cn.tedu.oa_system.base.json_result.ResultDataDto;
import cn.tedu.oa_system.base.json_result.ResultDto;
import cn.tedu.oa_system.base.util.SessionUtil;
import cn.tedu.oa_system.mapper.UserLoginRecordMapper;
import cn.tedu.oa_system.mapper.UserMapper;
import cn.tedu.oa_system.pojo.UserLoginRecord;
import cn.tedu.oa_system.pojo.in.LoginIn;
import cn.tedu.oa_system.pojo.model.UserInfo;
import cn.tedu.oa_system.service.LoginService;
import cn.tedu.oa_system.service.UserService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private SessionUtil sessionUtil;

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserLoginRecordMapper userLoginRecordMapper;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    public ResultDataDto<String> login(@RequestBody LoginIn loginIn, HttpServletRequest req){
        log.debug("正在尝试访问的用户名:({})",loginIn.getUsername());
        ResultDataDto<String> resultDto = new ResultDataDto<>();
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(loginIn,userInfo);
        String token = loginService.login(userInfo);

        //将用户登录信息添加到用户登录记录表
        UserLoginRecord loginRecord=new UserLoginRecord();
        //获取ip
        String ip=null;
        try {
            ip= InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        UserInfo infoByUsername = userMapper.getUserInfoByUsername(userInfo.getUsername());

        loginRecord.setLoginTime(new Date());
        loginRecord.setBrowser(req.getHeader("User-Agent"));
        loginRecord.setIpAddr(ip);
        loginRecord.setUserId(infoByUsername.getId());

        userLoginRecordMapper.insert(loginRecord);

        resultDto.setDataList(infoByUsername.getPermissions());
        resultDto.setData(token);
        resultDto.setIsSuccess(true);
        return resultDto;
    }

}
